import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart'hide Action;
import 'package:flutter/widgets.dart'hide Action;
import 'package:oktoast/oktoast.dart';
import 'package:school_safe_teacher/Home/entity/news_entity.dart';
import 'package:school_safe_teacher/base/entity_factory.dart';
import 'package:school_safe_teacher/constans/constants.dart';
import 'package:school_safe_teacher/network/dio_api.dart';
import 'package:school_safe_teacher/network/http_api.dart';


import 'action.dart';
import 'entity/message_entity.dart';
import 'state.dart';

Effect<MessageState> buildEffect() {
  return combineEffects(<Object, Effect<MessageState>>{
    MessageAction.onRefresh: _onRefresh,
    MessageAction.onLoad: _onLoad,
    MessageAction.readAll:_readAll,
  });
}

void _readAll(Action action, Context<MessageState> ctx){
  Map<String, String> params = Map();
  DioApi.instance.asyncRequestNetwork<NewsEntity>(
      Method.post, HttpApi.MESSAGE_READ_ALL, ctx.context,params: params, onStart: () {},
      onSuccessList: (List<dynamic> list) async {
        ctx.state.easyRefreshController.callRefresh();
        ctx.broadcast(MessageActionCreator.onRefreshHomeNum());
      }, onError: (String msg) {
    showToast(msg);
  }, onDone: () {
    ctx.dispatch(MessageActionCreator.onComplete());
  }, isList: true);
}

void _onRefresh(Action action, Context<MessageState> ctx) {
  _request(ctx, 1);
}

void _onLoad(Action action, Context<MessageState> ctx) {
  _request(ctx, action.payload);
}

void _request(Context<MessageState> ctx, int page) {
  Map<String, String> params = Map();
  params["limit"] = Constants.PAGE_SIZE.toString();
  params["page"] = page.toString();
  DioApi.instance.asyncRequestNetwork<NewsEntity>(
      Method.post, HttpApi.MESSAGE_LIST, ctx.context,params: params, onStart: () {},
      onSuccessList: (List<dynamic> list) async {
        List<MessageEntity> newsList = [];
        list.forEach((element) {
          newsList.add(EntityFactory.generateOBJ(element));
        });
        ctx.dispatch(MessageActionCreator.onSuccess(newsList));
      }, onError: (String msg) {
    showToast(msg);
  }, onDone: () {
    ctx.dispatch(MessageActionCreator.onComplete());
  }, isList: true);
}
